/*
 * Copyright (c) 2009 Nathaniel Houghton <nathan@brainwerk.org>
 *                    Robert Kirchgessner <rkirchge@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for
 * any purpose with or without fee is hereby granted, provided that
 * the above copyright notice and this permission notice appear in all
 * copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
 * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
 * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 *
 */
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#include "ui.h"
#include "usart.h"
#include "mode.h"
 
void
elm_mode(struct mode *mode)
{
	int c;
	static int escape_count;
	char buf[32];
	
	switch (mode->state) {
	case STATE_0_INIT:
		escape_count = 0;
		usart_echo(0, 0);
		snprintf(buf, sizeof(buf), "Mode: %s",
			mode_str[mode->mode]);
		lcd_update(&lcd, 0, buf);
		lcd_update(&lcd, 1, "");
		change_state(mode, 1);
		break;

	case 1:
		while (usart_rxused(0) > 0) {
			c = usart_getc(0);
			if (c == '!')
				++escape_count;
			else {
				usart_putc(1, c);
				escape_count = 0;
			}
		}

		while (usart_rxused(1) > 0) {
			c = usart_getc(1);
			usart_putc(0, c);
		}

		if (escape_count == 3)
			change_mode(mode, MODE_CONFIG);
		break;

	case STATE_FF_END:
		usart_echo(0, 1);
		break;
	}
}
